<?php

class UserController extends Controller
{

    private $userService = null;

    function __construct($id)
    {
        parent::__construct($id);
        $this->userService = new UserService();
    }

    public function beforeAction($action)
    {
//        $uid = isset($_GET["uid"])?$_GET["uid"]:(isset($_POST["uid"])?$_POST["uid"]:null);
//        if($uid !== null){
//            $uri = "app/user/".$this->getAction()->getId();
//            $token = isset($_GET["token"])?$_GET["token"]:(isset($_POST["token"])?$_POST["token"]:null);
//            if($token===null){
//                JSONHelper::echoJSON(false,  JSONHelper::ERROR_ILLEGAL_REQUEST);
//            }
//            if($token != SafeVerfiy::getKey($uid, $uri)){
//                JSONHelper::echoJSON(false,  JSONHelper::ERROR_ILLEGAL_REQUEST);
//            }
//        }
        return TRUE;
    }

    /**
     * app注册接口(新)
     * @param $POST ["username"] 当前就是手机号
     * @param $POST ["password"] 密码
     * @param $POST ["realname"] 姓名
     * @param $POST ["idcard"] 身份证号
     */
    public function actionSignup()
    {
        $result = $this->userService->signup($_POST);

        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true, $result);
    }

    /**
     * app修改个人信息接口(新)
     * @param $POST ["uid"] uid
     * @param $POST ["realname"] 姓名
     * @param $POST ["oldpass"] 旧密码
     * @param $POST ["newpass"] 新密码
     * @param $POST ["idcard"] 身份证号
     */
    public function actionModifyInfo()
    {
        $result = $this->userService->modifyInfo($_POST);

        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        echo JSONHelper::retInfo(true, $result);
    }

    /**
     * app修改个人信息接口(新)
     * @param $POST ["uid"] uid
     * @param $POST ["realname"] 姓名
     * @param $POST ["oldpass"] 旧密码
     * @param $POST ["newpass"] 新密码
     * @param $POST ["idcard"] 身份证号
     */
    public function actionModifyPwd()
    {
        $result = $this->userService->modifyPwd($_POST);

        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true, $result);
    }

    /**
     * app 端注册接口
     * @param $POST ["user"]["idcard"]:身份证
     * @param $POST ["user"]["name"]:姓名
     * @param $POST ["user"]["email"]:邮箱
     * @param $POST ["user"]["telephone"]:手机
     * @param $POST ["user"]["password"]:密码
     * @return ERROR_CODE Description
     */
    public function actionRegister()
    {
        $result = $this->userService->register($_POST);

        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        echo JSONHelper::retInfo(true, $result);
    }

    public function actionIndex()
    {
        $this->render('register');
    }

    /*
     * 登录接口
     * @param $user[username]: 手机号
     * @param user[password]：密码            
     */

    public function actionVerify()
    {
        $params = isset($_POST["user"]) ? $_POST["user"] : array();
        $result = $this->userService->verify($params);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        echo JSONHelper::retInfo(true, $result);
    }

    /**
     * 获取用户预约的套餐信息及体检中心
     * $_POST["uid"] 用户uid
     */
    public function actionGetpackageandcenter()
    {
        $result = $this->userService->getPackageAndCenter($_GET);

        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true, $result);
    }

    /**
     * 获取某一次ticket预约详情，此接口封掉， 全部用checkticket接口
     */
//    public function actionGetticketdetails(){
//        $result = $this->userService->getTicketDetails($_GET);
//
//        if (is_int($result)) {
//            JSONHelper::echoJSON(false, $result);
//        }
//        JSONHelper::echoJSON(true, $result);
//    }
    /**
     * 预约提交接口
     * @param appoint [userID]:用户id
     * @param appoint [subCenterID]:子体检中心id
     * @param appoint [date]:预约时间
     * 返回 预约结果字符串
     */
    public function actionAppointment()
    {
        $result = $this->userService->appointment($_POST);

        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true);
    }

    /**
     * 激活码兑换~或者身份证+姓名兑换
     * 返回 预约结果字符串
     */
    public function actionCheckTicket()
    {
        $result = $this->userService->checkTicket($_POST);

        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true, $result);
    }

    /*
     * 查询预约结果
     * 参数 $_POST['uid']
     * 返回 用户订单的json字符串
     */

    public function actionGetMyOrder()
    {
        $result = $this->userService->getMyOrder($_GET);

        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        echo JSONHelper::retInfo(true, $result);
    }

    /*
     * 功能：输出制定地点周围的体检中心
     * 参数：uid-用户id，lat-当前的维度, lon-当前的经度，radius-查找范围(单位是米)
     * 返回：范围内体检中心信息列表的json串
     */

    public function actionCenterSearch()
    {
        $result = $this->userService->centerSearch($_GET);

        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        echo JSONHelper::retInfo(true, $result);
    }

    /**
     * 取消预约
     */
    public function actionCancelbooking()
    {
        $result = $this->userService->cancelBooking($_POST);

        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        echo JSONHelper::retInfo(true);
    }

    public function actionPwdReset()
    {
        $result = $this->userService->pwdReset($_POST);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true);
    }

    /*
     * 找回密码功能
     * @param username  用户名
     */

    public function actionGetPassword()
    {

        $result = $this->userService->getPassword($_POST);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true);
    }

    /**
     * 获取体检报告列表
     */
    public function actionGetReportList()
    {
        $result = $this->userService->getReportList($_GET);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true, $result);
    }

    /**
     * 体检报告转发
     */
    public function actionReportForward()
    {
        $result = $this->userService->reportForward($_POST);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true);
    }

    /**
     *
     */
    public function actionGetSmsCaptcha()
    {
        $result = $this->userService->getSmsCaptcha($_POST);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true);
    }

    /**
     *
     */
    public function actionGetReportWithSmsCaptcha()
    {

        $result = $this->userService->getReportWithSmsCaptcha($_POST);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        $item["url"] = $this->createAbsoluteUrl("app/user/reportView", $_POST);
        JSONHelper::echoJSON(true, $item);
    }

    /**
     * 查看体检报告详情
     */
    public function actionReportView()
    {
//        if(!isset($_GET["uid"])||!isset($_GET["orderid"])){
//            echo "非法请求";
//            return;
//        }
        /*
          $ret = B2bOrder::model()->findByPk($_GET["orderid"]);
          if(null === $ret){
          echo "不存在的订单请求";
          return;
          }
          if($ret->customer_id != $_GET["uid"]){
          echo "您没有权限查看此报告";
          return;
          }
          if($ret->status != 5){
          echo "您的电子报告尚未准备完毕，请耐心等待";
          return;
          }
          $this->layout = "//layouts/mobile";
          $this->render("reportview");
          // */
        if(isset($_GET["reportid"])&&$_GET["reportid"]<1){
            $this->renderPartial("reportExample");
            Yii::app()->end();
        }
        
        if (isset($_GET['uid'])&&$_GET['uid'] > 0) {
            $rows = $this->userService->getReportInfo($_GET);
            if (is_int($rows)) {
                throw new CHttpException(200, "请检查您请求的参数，系统开了个小差哦", $rows);
            }
        } else {
            $objects = array();
            $rows = Yii::app()->session['saveitems'];

            foreach ($rows as $key => $row) {
                $indicate_names[$row['name']] = $row['name'];
                $rowstemp[$row['name']] = $row;

            }
            $rows = $rowstemp;
            $indicate_results = Indicator::model()->findAllByAttributes(array("name" => $indicate_names));
            foreach ($indicate_results as $indicate_result) {
                $indicate_ids[$indicate_result->name] = $indicate_result->id;
            }
            foreach ($rows as $key => $value) {
                if (isset($indicate_ids[$key])) {
                    $value['indicator'] = new CObject(array('id' => $indicate_ids[$key]));
                } else {
                    $value['indicator'] = null;
                }
                $cobject = new CObject($value);
                array_push($objects, $cobject);
            }
            $rows = $objects;
        }
        /*
          Array
          (
          [0] => stdClass Object
          (
          [type] => 0
          [parent_name] => basic
          [name] => 用户姓名
          [value] => 王树荣
          [issue] =>
          [normal] =>
          [unit] =>
          )

          [1] => stdClass Object
          (
          [type] => 0
          [parent_name] => basic
          [name] => 性别
          [value] => 女
          [issue] =>
          [normal] =>
          [unit] =>
          )
          )
          转成一个表格
          basicxxx
          表格的行

          一般性检查
          表格的行
         */
        $result = array();
        foreach ($rows as $arow) {

            if (!isset($result[$arow->parent_name])) {
                $result[$arow->parent_name]["items"] = array();
                $result[$arow->parent_name]["issue"] = 0;
            }
            if ($arow->issue != "") {
                $result[$arow->parent_name]["issue"]++;
            }
            $result[$arow->parent_name]["items"][] = $arow;
        }
        $this->renderPartial("reportview", array("result" => $result));

        /* modified by CodeJam.
         * please add your coding to deal with errors
         */
    }

    /**
     * 查看体检报告详情
     */
    public function actionReportIn()
    {
    	
//        if(!isset($_GET["uid"])){
//            throw new CHttpException(200,"用户ID");
//        }

        $uid = isset($_GET["uid"]) && ($_GET['uid'] > 0) ? $_GET['uid'] : '';
        $report = new ReportService();
        if (isset($_POST["age"])) {

            $realname = empty($_POST['realname'])?'':trim($_POST["realname"]);

            $examdate = trim($_POST["examdate"]);
            
            // if ($examdate == "") {
            //     JSONHelper::echoJSON(false, "请选择体检日期");
            // }


            $list = $report->getReportList();
            foreach ($list as $it) {
                $items[$it["name"]] = $it;
            }
            $saveitems = array();
            foreach ($_POST as $key => $it) {
                $value = trim($it);
                if ($value == "") {
                    continue;
                }
                switch ($key) {
                    case "realname":
                        $item["name"] = "姓名";
                        $item["parent_name"] = "basic";
                        break;
                    case "gender":
                        $item["name"] = "性别";
                        $item["parent_name"] = "basic";
                        break;
                    case "examdate":
                        $item["name"] = "体检日期";
                        $item["parent_name"] = "basic";
                        break;
                    case "idcard":
                        $item["name"] = "身份证";
                        $item["parent_name"] = "basic";
                        break;
                    case "age":
                        $item["name"] = "年龄";
                        $item["parent_name"] = "basic";
                        break;
                        break;
                    default:
                        $item = $items[$key];
                        break;
                }
                $item["value"] = $value;
                array_push($saveitems, $item);
            }

            if (empty($uid)) {
                foreach ($saveitems as &$it) {
                    $value = $it["value"];
                    $normal = isset($it["normal"]) ? $it["normal"] : "";

                    if (strpos($normal, "~") !== false) {

                        $v = explode("~", $normal);
                        if ((float)$value < (float)$v[0]) {
                            $it["issue"] = "↓";
                        } elseif ((float)$value > (float)$v[1]) {
                            $it["issue"] = "↑";
                        }
                    }
//                $issue = isset($it["issue"])?$it["issue"]:"";
//                $unit = isset($it["unit"])?$it["unit"]:"";
                }
                Yii::app()->session["saveitems"] = $saveitems;

                $ret = true;
                $re = new CObject(array('id' => 1));
            } else {

                $re = new EvaluateReportLog();
                $re->uid = $uid;
                $re->type = EvaluateReportLog::TYPE_USER;
                if ($re->save() === false) {
                    throw new CHttpException(200, "服务器异常");
                }
                $re->no = date("YmdHis") . sprintf("%06d", $re->id);
                if ($re->update() === false) {
                    throw new CHttpException(200, "服务器异常update");
                }
                $ret = $report->saveUserReport($uid, $re->no, $saveitems);
            }
            if (false === $ret) {
                JSONHelper::echoJSON(false, "保存体检项目失败");
            }
            JSONHelper::echoJSON(TRUE, $re->id);
        }

//        if (Yii::app()->session["saveitems"] != null) {
//            $ret = Yii::app()->session["saveitems"];
//            
//        }else{
            $ret = $report->getReportList();
//        }
//        var_dump($ret);
        $items = array();
        foreach ($ret as $it) {
            isset($items[$it["parent_name"]]) ? "" : $items[$it["parent_name"]] = array();
            array_push($items[$it["parent_name"]], $it);
        }
        
//        echo "<pre>";var_dump($items);echo "</pre>";exit();
        $this->renderPartial("reportIn", array("result" => $items));

        /* modified by CodeJam.
         * please add your coding to deal with errors
         */
    }

    public function actionGetUserIssue()
    {
        $result = $this->userService->getUserIssue($_REQUEST);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true, $result);
    }

    public function actionReportDel()
    {
        $result = $this->userService->ReportDel($_REQUEST);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true);
    }

    /**
     * 健康指导.
     * 1. 将'原始体检报告'里面的文字性解释拿出来
     * 2. 不正常指标，从我们自己的exam_item/ indicator里面拼接出来
     * 3. render the whole view
     *
     * @param uid eg. 32
     * @param orderid eg.1
     */
    public function actionReportAna()
    {
        $content = null;
        if (!isset($_GET["uid"]) || !isset($_GET["orderid"])) {
            $content = "非法请求";
        }
        $ret = B2bOrder::model()->findByPk($_GET["orderid"]);
        if (null === $ret) {
            $content = "不存在的订单请求";
        }
        if ($ret->customer_id != $_GET["uid"]) {
            $content = "您没有权限查看此报告";
        }
        if ($ret->status != 5) {
            $content = "您的电子报告尚未准备完毕，请耐心等待";
        }
        if (null === $content) {
            // TODO 把每个不正常的体检项目，通过exam item表解读出来
            $content = $this->userService->reportana($_GET);
        }

        $this->layout = "//layouts/mobile";
        $this->render("reportana", array("content" => $content));
    }

    /**
     * 绑定用户与设备
     */
    public function actionBindUserDevice()
    {
        $result = $this->userService->setUserDevice($_REQUEST);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true, $result);
    }

    /*
     * 用户下订单
     */

    public function actionSetPurchaseRecords()
    {
        $result = $this->userService->setPurchaseRecords($_POST);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true, $result);
    }

    /**
     * 消息列表
     */
    public function actionGetMsgList()
    {
        $result = $this->userService->getMsgList($_GET);
        if (is_int($result)) {
            JSONHelper::echoJSON(false, $result);
        }
        JSONHelper::echoJSON(true, $result);
    }

}
